package itsm.isperp.module.service.wechat;

import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.wechat.WechatChat;
import itsm.isperp.module.repository.wechat.WechatChatMapper;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class WechatChatService extends BaseService<WechatChat> {

	@Autowired
	protected WechatChatMapper wechatChatMapper;
	@Autowired
	protected JdbcTemplate jdbcTemplate;

	@Override
	public WechatChatMapper getRepository() {
		return this.wechatChatMapper;
	}

	public List<Map<String, Object>> findAllGroupByOpenid() {
		return wechatChatMapper.findAllGroupByOpenid();
	}

	public List<WechatChat> listChats(String openid) {
		return wechatChatMapper.listChats(openid);
	}

	public List<WechatChat> findByRelationId(String relationId) {
		JqGridRequest req = new JqGridRequest();
		req.addFilterRule("relation_id", JqGridFilterRuleOp.eq, relationId);
		req.isPageable(false);

		return wechatChatMapper.findAllByRequest(req);
	}

	public List<WechatChat> findNotRelationByOpenid(String openid) {
		JqGridRequest req = new JqGridRequest();
		req.addFilterRule("openid", JqGridFilterRuleOp.eq, openid);
		req.addFilterRule("relation_id", JqGridFilterRuleOp.isnull, "");
		req.isPageable(false);

		return wechatChatMapper.findAllByRequest(req);
	}

	public void relationToObject(String openid, String id) {

		String sql1 = "UPDATE app_upload_file SET source_id='"
				+ id
				+ "' WHERE id IN(SELECT app_upload_file_id FROM wechat_chat WHERE openid='"
				+ openid
				+ "' AND relation_id IS NULL AND msg_type IN('image','video','voice'))";
		jdbcTemplate.update(sql1);

		String sql2 = "UPDATE wechat_chat SET relation_id='" + id
				+ "' WHERE openid='" + openid + "'";
		jdbcTemplate.update(sql2);
		
	}
}
